package cn.itcast.interceptor;


import cn.itcast.pojo.Member;
import cn.itcast.utils.JwtUtils;
import cn.itcast.utils.ThreadLocalUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//------------------------------拦截器--------------------------------
//------------------------------ThreadLocal-------------------------------
/**
 * 1. 在拦截下的请求路径里进行token解析和校验
 * 优化了每个业务都需要解析token,校验token的问题
 * 使得业务代码更加简洁
<<<<<<< HEAD:chaunzhi-health/itcast-health-parent/itcast-health-mobile/src/main/java/cn/itcast/interceptor/TokenIntector.java
 * 2. ThreadLocal 将Member对象存储到ThreadLocal线程中 业务结束及删除数据*/


public class TokenIntector implements  HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 获取请求头中的token ,
        String token = request.getHeader("token");
        //2. 通过工具类,判断token是否有效
        boolean verifyToken = JwtUtils.verifyToken(token);
        //3.token失效 返回异常状态码 拦截
        if (!verifyToken){
            response.setStatus(401);
            return false;
        }
        //4. token有效, 放行
        //解析token 获取id和手机号码 创建User对象,存入ThreadLocal
        Claims claims= JwtUtils.getClaims(token);
        String phone = (String) claims.get("phone");
        Integer id = (Integer) claims.get("id");

        Member member=new Member();
        member.setPhoneNumber(phone);
        member.setId(id);

        //把user对象 存储到ThreadLocal线程中
        ThreadLocalUtils.setUser(member);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtils.remove();

    }




}

